package book;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Socket_book {
    DatagramSocket socket;
    int port;

    public Socket_book(int port) {
        this.port = port;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }

    void start() {
        while (true) {
            DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
            try {
                socket.receive(packet);//抛出异常IOException

                //获得packet中的有效数据，有可能这个数组没有装满
                String msg = new String(packet.getData(), 0, packet.getLength());

                //对数据进行操作 这里直接返回的就是msg run里就写的是业务代码
                String ret = run(msg);

                //将数据的包装必过发送
                DatagramPacket packet2 = new DatagramPacket(ret.getBytes(), 0, ret.length(),
                        packet.getAddress(), packet.getPort());
                //发送
                socket.send(packet2);

                System.out.println("请求完成");

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private String run(String msg) {
        return msg;
    }

    public static void main(String[] args) {
        //创建对象
        Socket_book socketBook = new Socket_book(8888);

        //启动
        socketBook.start();

        //结束
        System.out.println("断开");
    }

}
